<?php

namespace model;

use common\Model;

class attments extends Model
{

	const TABLE = "attments";
	private $DB;
    function __construct()
    {
        $this->DB = parent::db();
    }
	//关联查找一条数据
	public function findData()
	{
		return $this->DB->table(self::TABLE)->where(['id' => $_POST['id']])->find();
	}

	//添加数据
	public function insertData($atturl, $priname, $ext, $size)
	{
		$data = [
			'atturl' => $atturl,
			'userid' => LoginUserInfo("userid"),
			'priname' => $priname,
			'ext' => $ext,
			'size' => $size,
		];
		return $this->DB->table(self::TABLE)->insert($data);
	}

	//删除一条数据
	public function deleteOneData()
	{
		$where['attid'] = $_GET['attid'];
		$find = $this->DB->table(self::TABLE)->where($where)->find();
		if ($find) {
			DelFile($find['atturl']); //删除文件
			SqlLog("删除附件 ID：" . $find['attid'] . " 路径：" . $find['atturl']); //写入日志
			return $this->DB->table(self::TABLE)->where($where)->Delete();
		} else {
			return false;
		}
	}

	//获取数据并分页
	public function jsonPageSelect()
	{
		$p = intval($_GET['page'] ?? 0) ?: 1;
		$num = intval($_GET['limit'] ?? 0) ?: 15;

		$page = ['num' => $num, 'p' => $p, 'return' => true];
		$field = 'b.id as uid,b.username,a.attid,a.userid,a.atturl,a.priname,a.ext,a.size';
		$join = 'LEFT JOIN admin_user b ON a.userid=b.id';

		return [
			'data' => $this->DB->table(self::TABLE. ' a')->field($field)->join($join)->Page($page)->order('attid DESC')->select(),
			'page' => $this->DB->getPage()
		];
	}
}
